﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace QD.Validate
{
    public class RangeRule<T> : IValidateRule<T> where T : struct, IComparable<T>
    {
        public Nullable<T> Min { get; set; }
        public Nullable<T> Max { get; set; }
        public Boolean LeftBound { get; set; }
        public Boolean RightBound { get; set; }
        public Boolean IsOutRange { get; set; }
        public String Tips { get; private set; }

        public RangeRule(Nullable<T> min, Nullable<T> max)
        {
            if (min.HasValue && max.HasValue)
                if (min.Value.CompareTo(max.Value) > 0) throw new Exception("MinValue must Lessthen Maxvalue");
            this.Min = min; this.Max = max;
        }

        public Boolean IsValidate(T value)
        {
            Boolean valid = true;

            Int32 result = 0;

            if (Min.HasValue)
            {
                result = Min.Value.CompareTo(value);
                valid = result < 0;
                if (LeftBound)
                    valid = valid || result == 0;
            }

            if (Max.HasValue)
            {
                result = Max.Value.CompareTo(value);
                valid = valid && (result > 0);
                if (RightBound)
                    valid = valid || result == 0;
            }
            if (IsOutRange)
                valid = !valid;

            return valid;
        }
    }

}
